<template>
    <el-container class="row main">
        <el-alert
            v-if="saveLoading"
            title="正在保存当前操作"
            type="info"
            effect="dark">
        </el-alert>
        <el-aside width="140px" id="draw">
            <span class="label lable-primary">选择图形</span>
            <div class="draw-type-box">
                <icon @click.native="clickDraw(item.type)" :name="item.icon" scale="3" clas="icon" :title="item.type"
                    v-for="item in drawTypeList" :key="item.icon"></icon>
            </div>
            <span class="label lable-primary">选择主题</span>
            <div class="theme-plan-row">
                <div v-for="item in themeList" class="theme-plan-group" :key="item.name" :title="item.name"
                    @click="setTheme(item.name)" :style="'background-color:' + item.background">
                    <div v-for="color in item.color" class="theme-plan-color" :style="'background-color:' + color"
                        :key="color.type"></div>
                </div>
            </div>
        </el-aside>
        <el-main style="width: 0" v-loading="loading">
            <Grid v-if="type === 'table'" :rowData="tableViewData.data" :fieldList="tableViewData.fieldList" :page="tableViewData.page" :colorConfig="tableViewData.colorConfig"/>
            <div id="parent">
                <div id="chart" v-show="type !== 'table'" style="height: 500px;width: 500px"></div>
            </div>
        </el-main>
    </el-container>
</template>

<script>
import setEchartsOption from '@/views/commonView/js/setEchartsOption'
import Theme from '@/views/commonView/theme/theme.js'
import * as Echarts from 'echarts'
import Grid from './Grid'
import {Message} from 'element-ui'

let setEcharts = setEchartsOption.setEchartsOption
let themeSeting = Theme.theme
// 获取主题颜色配置
const getThemeColor = (name) => {
    const theme = require('./theme/json/' + name + '.json')
    const colors = theme.color.slice(0, 5)
    return { name, background: theme.backgroundColor, color: colors }
}
export default {
    name: 'DrawSetView',
    components: { Grid },
    props: ['chartData', 'unitId'],
    data() {
        return {
            tableViewData: {
                data: [],
                fieldList: [],
                page: {},
                colorConfig:{}
            },
            $echarts: null,
            type: '',
            option: '',
            themeName: '',
            loading:false,
            saveLoading:false,
            drawTypeList: [// 可选图形类型
                { type: 'bar', icon: 'bar1' }, // 柱
                { type: 'barLeft', icon: 'barLeft' },// 柱-横向
                { type: 'barStack', icon: 'bar3' }, // 柱-堆叠

                { type: 'line', icon: 'line1' },
                { type: 'lineArea', icon: 'line2' },
                { type: 'lineStack', icon: 'line3' },

                { type: 'lineStackArea', icon: 'line4' },
                { type: 'pie', icon: 'pie1' },
                { type: 'pieRose', icon: 'pie2' },

                { type: 'pieRing1', icon: 'pieRing' },
                { type: 'pieRing2', icon: 'pie3' },
                { type: 'radar', icon: 'radar' },

                { type: 'table', icon: 'table' },
            ],
            themeList: [// 可选主题
                getThemeColor('roma'),
                getThemeColor('westeros'),
                getThemeColor('essos'),
                getThemeColor('infographic'),
                getThemeColor('macarons'),
                getThemeColor('shine'),
                getThemeColor('vintage'),
                getThemeColor('walden'),
                getThemeColor('wonderland'),
                getThemeColor('purple-passion'),
                getThemeColor('chalk'),
                getThemeColor('dark'),
            ],
            lastData:{}
        }
    },
    methods: {
        // 点击图形
        clickDraw(type) {
            // 没有实例化之前不能调用
            if (!this.$echarts.setOption) return
            let chartData = this.chartData
            // 校验数据完整性
            if (chartData.data.fields || chartData.data.data) {
                let opt = setEcharts.readData(type, chartData)
                this.$echarts.setOption(opt, true)
                this.type = type
                this.option = opt
            }
            this.updateUnit2()
        },
        // 设置主题
        setTheme(themeName = 'roma') {
            console.log('主题',themeName)
            // 没有实例化之前不能调用
            if (!this.$echarts.setOption) return
            // 获取主题
            let obj = themeSeting.getTheme(themeName)
            if (obj) {
                this.tableViewData.colorConfig = {bg:obj.backgroundColor,color:obj.color}
                // 注册主题
                Echarts.registerTheme(themeName, obj)
                // 释放资源
                this.$echarts.dispose()
                // 重新实例化
                const chart = document.getElementById('chart')
                this.$echarts = Echarts.init(chart, themeName)
                this.$echarts.setOption(this.option, true)
                this.themeName = themeName
                this.updateUnit2()
            }

        },
        // 初始化echarts
        initEcharts(opt, themeName = 'roma', type) {
            let chart = document.getElementById('chart')
            let obj = themeSeting.getTheme(themeName)
            if (obj) {
                // 注册主题
                Echarts.registerTheme(themeName, obj)
            }
            this.$echarts = Echarts.init(chart,themeName)
            this.$echarts.setOption(opt)
            // 其他参数赋值
            this.type = type
            this.option = opt
            this.themeName = themeName
            this.initStatus = true
            // 默认保存一次
            this.updateUnit2()
        },
        // 更新组件
        updateUnit: function (vm) {
            let param = {
                unitId: vm.unitId,
                type: '1',
                pageNum: 1,
                pageSize: 15
            }
            // 保存数据之前需要查询数据
            vm.$http.post('/adhoc/dataUnits/dataUnitModify', param).then((res) => {
                let wd = []
                let dl = []
                let arr1 = res.data.body.textFields1
                let arr2 = res.data.body.numberFields
                let condition = res.data.body.condition

                arr1.forEach((v) => {
                    let a = {}
                    a.colEn = v.colEn
                    a.columnColor = '#33443322'
                    a.columnSharp = null
                    a.orderType = 'asc'
                    a.sortColName = 'id'
                    a.groupType = 'same'
                    a.groupId = '1'
                    a.showName = v.showName
                    a.beShow = 'true'
                    wd.push(a)
                })
                // 后端要求
                if (wd.length === 0) {
                    wd.push({})
                }

                arr2.forEach((v) => {
                    let a = {}
                    a.colEn = v.colEn
                    a.columnColor = '#33443322'
                    a.columnSharp = null
                    a.totalCalc = 'sum'
                    a.fastCalc = 'sum'
                    a.dataFormat = 'same'
                    a.beShow = 'true'
                    a.showName = v.showName
                    a.beShow = 'true'
                    dl.push(a)
                })
                // 后端要求
                if (dl.length === 0) {
                    dl.push({})
                }

                param.textFields1 = wd
                param.numberFields = dl
                // todo
                param.themes = vm.themeName
                param.widgets = vm.type
                param.condition = condition
                // 保存数据
                vm.$http.post('/adhoc/dataUnits/dataUnitModify', param).then((res) => {
                    if (res.data.code <= 400) {
                    }
                })
            })
        },
        // 更新组件
        updateUnit2() {
            if(this.saveLoading){
                return Message.warning('请等待上次操作保存完毕')
            }
            let param = {
                unitId: this.unitId,
                themes:this.themeName,
                widgets:this.type,
                condition:this.lastData.condition,
                textFields1:this.lastData.textFields1.map(item => {
                    item.columnColor = '#33443322'
                    item.columnSharp = null
                    item.orderType = 'asc'
                    item.sortColName = 'id'
                    item.groupType = 'same'
                    item.groupId = '1'
                    item.beShow = 'true'
                    return item
                }),
                numberFields:this.lastData.numberFields.map(item => {
                    item.columnColor = '#33443322'
                    item.columnSharp = null
                    item.totalCalc = 'sum'
                    item.fastCalc = 'sum'
                    item.dataFormat = 'same'
                    item.beShow = 'true'
                    item.beShow = 'true'
                    return item
                }),
                type: '1',
                pageNum: 1,
                pageSize: 15,
            }
            // 保存数据
            this.saveLoading = true
            this.$http.post('/adhoc/dataUnits/dataUnitModify', param).then((res) => {
                    Message.success('保存成功')
                }).finally(() => this.saveLoading = false)
        }
    },
    mounted() {
        if (this.unitId) {
            let param = {
                unitId: this.unitId,
                type: '1'
            }
            this.loading = true
            // 查询数据
            this.$http.post('/adhoc/dataUnits/dataUnitModify', param).then((res) => {
                const { data, fields, page, textFields1, numberFields, widgets, themes,condition } = res.data.body
                // 保存最后一次请求数据，提交的时候需要用到
                this.lastData = {textFields1, numberFields,condition}
                // 保存原始数据，供表格使用
                this.tableViewData = { data, fieldList: fields, page: page }
                // echart初始化需要的数据格式
                const echartData = {
                    textFields1,
                    numberFields,
                    data: { data: data }
                }
                // 没有定义图形类型，默认读取柱状图配置，避免页面空缺
                let opt = setEcharts.readData(widgets || 'bar', echartData)
                // 初始化echart图型
                if (opt) {
                    this.initEcharts(opt, themes, widgets|| 'bar')
                }
            }).finally(() => this.loading = false)
        }
    }
}
</script>

<style lang="less" scoped>
.main {
    height: 100%;
    padding: 5px;
    position: relative;
}
#parent {
    margin: 0 auto;
    min-width: 720px;
    overflow-x: auto;
    // border: 2px solid skyblue;
}
#draw {
    height: 100%;
    width: 100%;

    .draw-type-box {
        display: flex;
        justify-content: flex-start;
        flex-wrap: wrap;

        svg {
            width: 30%;
        }
    }
}
.theme-plan-row {
    -webkit-tap-highlight-color: rgba(0, 0, 0, 0);
    font-size: 14px;
    line-height: 1.42857143;
    color: #333;
    font-family: "Open Sans", "PingFang SC", Helvetica, Arial, sans-serif;
    text-align: left;
    box-sizing: border-box;
    .theme-plan-group {
        display: flex;
        justify-content: space-around;
        align-items: center;
        height: 24px;
        cursor: pointer;
    }
}
.theme-plan-color {
    width: 16px;
    height: 16px;
    display: inline-block;
    border-radius: 3px;
}
#chart {
    margin: 20px auto;
}
</style>
